import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
  UploadOutlined
} from '@ant-design/icons'
import { sensitiveWordsConfig } from '@renderer/config/sensitiveWords'
import FilterService from '@renderer/services/FilterService'
import type { UploadProps } from 'antd'
import { Checkbox } from 'antd'
import { Button, Flex, Input, message, Modal, Popconfirm, Space, Switch, Upload } from 'antd'
import { Tooltip } from 'antd'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'

import { SettingContainer, SettingDivider, SettingGroup, SettingRow, SettingRowTitle, SettingTitle } from '..'

interface SensitiveWord {
  id: string
  word: string
}

const SensitiveWordSettings: FC = () => {
  const { t } = useTranslation()
  const [wordsList, setWordsList] = useState<SensitiveWord[]>([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [editingWord, setEditingWord] = useState<SensitiveWord | null>(null)
  const [formData, setFormData] = useState({ word: '' })
  const [enabled, setEnabled] = useState(sensitiveWordsConfig.enabled)
  const [selectedWords, setSelectedWords] = useState<string[]>([])
  const [isAllSelected, setIsAllSelected] = useState(false)

  // 检查是否允许用户配置敏感词
  const isUserConfigAllowed = sensitiveWordsConfig.allowUserConfig

  // 加载敏感词列表
  const loadWords = () => {
    const words = sensitiveWordsConfig.words.map((word, index) => ({
      id: `word-${index}`,
      word
    }))
    setWordsList(words)
  }

  useEffect(() => {
    loadWords()
  }, [])

  useEffect(() => {
    setIsAllSelected(wordsList.length > 0 && selectedWords.length === wordsList.length)
  }, [selectedWords, wordsList])

  // 启用/禁用敏感词过滤
  const toggleSensitiveWordFilter = (checked: boolean) => {
    // 尝试设置敏感词过滤状态，如果设置成功则更新UI
    if (FilterService.setEnabled(checked)) {
      setEnabled(checked)
    }
  }

  // 添加敏感词
  const handleAdd = () => {
    setEditingWord(null)
    setFormData({ word: '' })
    setIsModalOpen(true)
  }

  // 编辑敏感词
  const handleEdit = (word: SensitiveWord) => {
    setEditingWord(word)
    setFormData({ word: word.word })
    setIsModalOpen(true)
  }

  // 删除敏感词
  const handleDelete = (id: string | string[]) => {
    const idsToDelete = Array.isArray(id) ? id : [id]
    const newWordsList = wordsList.filter((word) => !idsToDelete.includes(word.id))
    setWordsList(newWordsList)
    updateSensitiveWords(newWordsList.map((item) => item.word))
    setSelectedWords([]) // Clear selection after deletion
  }

  // 确认添加/编辑敏感词
  const handleModalOk = () => {
    if (!formData.word.trim()) {
      return
    }

    let newWordsList: SensitiveWord[]
    if (editingWord) {
      // 编辑现有敏感词
      newWordsList = wordsList.map((word) => {
        if (word.id === editingWord.id) {
          return { ...word, word: formData.word.trim() }
        }
        return word
      })
    } else {
      // 添加新敏感词
      const newId = `word-${Date.now()}`
      newWordsList = [...wordsList, { id: newId, word: formData.word.trim() }]
    }

    setWordsList(newWordsList)
    updateSensitiveWords(newWordsList.map((item) => item.word))
    setIsModalOpen(false)
  }

  // 更新敏感词列表到配置
  const updateSensitiveWords = (words: string[]) => {
    // 尝试更新敏感词列表，如果更新失败则重新加载原始列表
    if (!FilterService.updateSensitiveWords(words)) {
      loadWords() // 恢复原始列表
      message.error(t('settings.sensitiveWord.updateFailed'))
    }
  }

  // 文件上传处理
  const uploadProps: UploadProps = {
    name: 'file',
    accept: '.txt',
    showUploadList: false,
    beforeUpload: (file) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const text = e.target?.result as string
        if (text) {
          const newWords = text
            .split(/\r?\n/)
            .map((word) => word.trim())
            .filter((word) => word)
          const currentWords = wordsList.map((item) => item.word)
          const uniqueNewWords = newWords.filter((word) => !currentWords.includes(word))
          if (uniqueNewWords.length > 0) {
            const newWordObjects = uniqueNewWords.map((word) => ({ id: `word-${Date.now()}-${Math.random()}`, word }))
            const updatedWordsList = [...wordsList, ...newWordObjects]
            setWordsList(updatedWordsList)
            updateSensitiveWords(updatedWordsList.map((item) => item.word))
            message.success(t('settings.sensitiveWord.batchAddSuccess', { count: uniqueNewWords.length }))
          } else {
            message.info(t('settings.sensitiveWord.batchAddNoNew'))
          }
        }
      }
      reader.readAsText(file)
      return false // 阻止自动上传
    }
  }

  // 如果不允许用户配置敏感词，则显示提示信息
  if (!isUserConfigAllowed) {
    return (
      <SettingContainer>
        <SettingGroup style={{ marginBottom: 0 }}>
          <SettingTitle>{t('settings.sensitiveWord.title')}</SettingTitle>
          <SettingDivider />
          <SettingRow>
            <EmptyText style={{ color: 'var(--color-warning)' }}>
              {t('settings.sensitiveWord.configDisabled')}
            </EmptyText>
          </SettingRow>
        </SettingGroup>
      </SettingContainer>
    )
  }

  return (
    <SettingContainer>
      <SettingGroup style={{ marginBottom: 0 }}>
        <SettingTitle>
          {t('settings.sensitiveWord.title')}
          <Space>
            <Upload {...uploadProps}>
              <Tooltip title={t('settings.sensitiveWord.batchAddTips')} mouseEnterDelay={0.8}>
                <Button icon={<UploadOutlined />}>{t('settings.sensitiveWord.batchAdd')}</Button>
              </Tooltip>
            </Upload>
            <Button type="text" icon={<PlusOutlined />} onClick={handleAdd} />
            {selectedWords.length > 0 && (
              <Popconfirm
                title={t('settings.sensitiveWord.deleteSelected')}
                description={t('settings.sensitiveWord.deleteSelectedConfirm', { count: selectedWords.length })}
                okText={t('common.confirm')}
                cancelText={t('common.cancel')}
                onConfirm={() => handleDelete(selectedWords)}
                icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}>
                <Button danger icon={<DeleteOutlined />}>
                  {t('settings.sensitiveWord.deleteSelectedButton', { count: selectedWords.length })}
                </Button>
              </Popconfirm>
            )}
          </Space>
        </SettingTitle>
        <SettingDivider />

        <SettingRow>
          <SettingRowTitle>{t('settings.sensitiveWord.enable')}</SettingRowTitle>
          <Switch checked={enabled} onChange={toggleSensitiveWordFilter} />
        </SettingRow>

        <SettingDivider />
        {wordsList.length > 0 && (
          <SettingRow>
            <Checkbox
              checked={isAllSelected}
              onChange={(e) => {
                if (e.target.checked) {
                  setSelectedWords(wordsList.map((w) => w.id))
                } else {
                  setSelectedWords([])
                }
                setIsAllSelected(e.target.checked)
              }}>
              {t('settings.sensitiveWord.selectAll')}
            </Checkbox>
          </SettingRow>
        )}
        <SettingRow>
          <SensitiveWordList>
            {wordsList.length === 0 ? (
              <EmptyText>{t('settings.sensitiveWord.empty')}</EmptyText>
            ) : (
              wordsList.map((word) => (
                <WordItem key={word.id} selected={selectedWords.includes(word.id)}>
                  <Checkbox
                    checked={selectedWords.includes(word.id)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedWords([...selectedWords, word.id])
                      } else {
                        setSelectedWords(selectedWords.filter((id) => id !== word.id))
                      }
                    }}
                    style={{ marginRight: '12px' }}
                  />
                  <WordText>{word.word}</WordText>
                  <Flex gap={4} style={{ opacity: 0.6, marginLeft: 'auto' }}>
                    <Button key="edit" type="text" icon={<EditOutlined />} onClick={() => handleEdit(word)} />
                    <Popconfirm
                      title={t('settings.sensitiveWord.delete')}
                      description={t('settings.sensitiveWord.deleteConfirmSingle')}
                      okText={t('common.confirm')}
                      cancelText={t('common.cancel')}
                      onConfirm={() => handleDelete(word.id)}
                      icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}>
                      <Button key="delete" type="text" danger icon={<DeleteOutlined />} />
                    </Popconfirm>
                  </Flex>
                </WordItem>
              ))
            )}
          </SensitiveWordList>
        </SettingRow>
      </SettingGroup>

      <Modal
        title={editingWord ? t('settings.sensitiveWord.edit') : t('settings.sensitiveWord.add')}
        open={isModalOpen}
        onOk={handleModalOk}
        onCancel={() => setIsModalOpen(false)}
        width={400}>
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div>
            <Label>{t('settings.sensitiveWord.word')}</Label>
            <Input
              placeholder={t('settings.sensitiveWord.placeholder')}
              value={formData.word}
              onChange={(e) => setFormData({ word: e.target.value })}
            />
          </div>
        </Space>
      </Modal>
    </SettingContainer>
  )
}

const Label = styled.div`
  font-size: 14px;
  color: var(--color-text);
  margin-bottom: 8px;
`

const SensitiveWordList = styled.div`
  width: 100%;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px 0;
`

const WordItem = styled.div<{ selected?: boolean }>`
  display: flex;
  align-items: center; // Changed from justify-content: space-between to align-items for better checkbox alignment
  padding: 8px 12px;
  border-radius: 6px;
  background-color: ${(props) => (props.selected ? 'var(--color-primary-highlight)' : 'var(--color-background-soft)')};
  border: 1px solid var(--color-border);
  cursor: pointer;

  &:hover {
    background-color: var(--color-primary-highlight);
  }
`

const WordText = styled.div`
  font-size: 14px;
  color: var(--color-text);
`

const EmptyText = styled.div`
  width: 100%;
  text-align: center;
  padding: 20px 0;
  color: var(--color-text-3);
  font-size: 14px;
`

export default SensitiveWordSettings
